//
//  LocalCache.m
//  HomeFurnishingDecoration
//
//  Created by 李劲成 on 16/4/28.
//  Copyright © 2016年 ljc. All rights reserved.
//

#import "LocalCache.h"
#import "SandboxHandler.h"

@interface LocalCache ()

@property (nonatomic, strong) NSCache *memCache;
/** 本地缓存路径 */
@property (nonatomic, copy) NSString *diskCachePath;
/** 存放多个自定义路径的数组 */
@property (nonatomic, strong) NSMutableArray *customPaths;

@end


@implementation LocalCache

{
    
    NSFileManager *_fileManager;
}



#pragma mark - 单例方法
+ (instancetype)sharedLocalCache {
    
    static id instance;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [self new];
    });
    
    return instance;
}
#pragma mark - 构造器和自定义初始化
- (instancetype)init {
    // 默认路径
    return [self initWithNamespace:@"default"];
}


- (id)initWithNamespace:(NSString *)nameSpace {
    
    self = [super init];
    if (self) {
        
        // 拼接完整命名.
        NSString *fullNameSpaces = [@"HomeApp" stringByAppendingString:nameSpace];
  
        // 初始化磁盘缓存路径.
        self.diskCachePath = [self makeDiskCachePath:fullNameSpaces];
        // 创建文件管理对象.
        NSLog(@"%@", _diskCachePath);
            _fileManager = [NSFileManager defaultManager];
      
    }
    return self;
}

#pragma mark - 磁盘缓存路径(文件夹)
- (NSString *)makeDiskCachePath:(NSString *)fullNamespace {
    
    // 路径在缓存文件夹中.
  
   return [SandboxHandler pathForDirectory:Caches WithFileName:fullNamespace];

    
}

#pragma mark - 缓存路径.(文件)
/**
 @brief 获取文件缓存路径
 
 @param key  文件名
 
 @return 文件路径
 */
- (NSString *)cachePathForKey:(NSString *)key{
    
    
   
    return [self.diskCachePath stringByAppendingPathComponent:key];
    
    
}

#pragma mark - 检查磁盘中是否含有文件
- (BOOL)diskfileExistsWithKey:(NSString *)key {
    
    BOOL existes = NO;
    
    if (!key) {
        return existes;
    }
    existes = [_fileManager fileExistsAtPath:[self cachePathForKey:key]];
    
    return existes;

}

#pragma mark - 存储数据
- (void)storeObject:(id)object toDiskforKey:(NSString *)key {

//     如果磁盘没有磁盘缓存路径
    if (![_fileManager fileExistsAtPath:_diskCachePath]) {
        BOOL create = [_fileManager createDirectoryAtPath:_diskCachePath withIntermediateDirectories:YES attributes:nil error:nil];
        if (create) {
//            NSLog(@"创建成功");
        }
        else {
            NSLog(@"文件夹创建失败");
        }
    }
//
      BOOL create = [_fileManager createFileAtPath:[self cachePathForKey:key] contents:nil attributes:nil];
        if (create) {
//            NSLog(@"创建成功");
        }
        else {
            NSLog(@"文件创建失败");
        }
//    }
//    // 数据保存在磁盘中.(归档)
   BOOL result = [NSKeyedArchiver archiveRootObject:object toFile:[self cachePathForKey:key]];
    if (result) {
//        NSLog(@"写入成功");
    }
    else {
        NSLog(@"写入失败");
    }
    
}

- (void)storeArray:(NSArray *)array toDiskforKey:(NSString *)key {

    //     如果磁盘没有磁盘缓存路径
    if (![_fileManager fileExistsAtPath:_diskCachePath]) {
        BOOL create = [_fileManager createDirectoryAtPath:_diskCachePath withIntermediateDirectories:YES attributes:nil error:nil];
        if (create) {
            //            NSLog(@"创建成功");
        }
        else {
            NSLog(@"文件夹创建失败");
        }
    }
    //
    BOOL create = [_fileManager createFileAtPath:[self cachePathForKey:key] contents:nil attributes:nil];
    if (create) {
        //            NSLog(@"创建成功");
    }
    else {
        NSLog(@"文件创建失败");
    }
    //    }
    //    // 数据保存在磁盘中.(归档)
   BOOL result = [array writeToFile:[self cachePathForKey:key] atomically:YES];
   
    if (result) {
        //        NSLog(@"写入成功");
    }
    else {
        NSLog(@"写入失败");
    }
    
}

#pragma mark - 读取缓存
- (id)readCachesFromDiskWithKey:(NSString *)key {
    if (![self diskfileExistsWithKey:key]) {
        NSLog(@"读取失败");
        return nil;
    }
    else {
          id result = [NSKeyedUnarchiver unarchiveObjectWithFile:[self cachePathForKey:key]];
      
        return result;
    }
}

- (NSArray *)readArrayFromDiskWithKey:(NSString *)key{
    if (![self diskfileExistsWithKey:key]) {
        NSLog(@"读取失败");
        return nil;
    }
    else {
        NSArray *array = [NSArray arrayWithContentsOfFile:[self cachePathForKey:key]];
        
        return array;
    }
}

- (void)removeFileWithKey:(NSString *)key{
    if ([self diskfileExistsWithKey:key]) {
      BOOL result = [_fileManager removeItemAtPath:[self cachePathForKey:key] error:nil];
        if (result) {
            NSLog(@"删除成功");
        }
        else{
            NSLog(@"删除失败");
        }
    }
}
#pragma mark - 删除缓存
- (void)clearData {
    if ([_fileManager fileExistsAtPath:_diskCachePath]) {
     BOOL result = [_fileManager removeItemAtPath:_diskCachePath error:nil];
        if (result) {
            NSLog(@"delete success");
        }
        else {
            NSLog(@"delete filed");
        }
    }
    [[SDImageCache sharedImageCache] clearDisk];
}

//获取单个文件的大小
- (float)fileSizeAtPath:(NSString *)path{
  
    if([_fileManager fileExistsAtPath:path]){
        long long size=[_fileManager attributesOfItemAtPath:path error:nil].fileSize;
        return size/1024.0/1024.0;
    }
    return 0;
}

//计算目录大小
- (float)folderSizeAtPath:(NSString *)path{
    CGFloat j;
    if ([_fileManager fileExistsAtPath:path]) {
        NSArray *files = [_fileManager subpathsAtPath:path];
        //遍历所有文件
        for (NSInteger i = 0; i < files.count; i++) {
            NSString *filePath = [path stringByAppendingPathComponent:files[i]];
            //获取文件大小
            float k = [[_fileManager attributesOfItemAtPath:filePath error:nil] fileSize];
            j =  j + k;
            
        }
    }
    return j/1024.0/1024.0;
}

#pragma mark - 计算所有缓存大小
- (float)folderSizeAtDefaultPath{
   CGFloat fileSize = [self folderSizeAtPath:_diskCachePath];
    CGFloat imageSize = [self folderSizeAtPath:[SandboxHandler pathForDirectory:Caches WithFileName:@"default"]];

    return fileSize + imageSize;
}

- (void)GETWithURL:(NSString *)urlStr Local:(void (^)(id localObj))localObj{
    
    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    //    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    //
    
    NSString *path = [NSString stringWithFormat:@"%ld",(unsigned long)[urlStr hash]];
    
    if ([self diskfileExistsWithKey:path]) {
        id result = [self readCachesFromDiskWithKey:path];
        localObj(result);
    }
    //    });
    
}
@end
